package com.dshore.messagecenter.service.basedata.impl;

import java.io.BufferedOutputStream;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dshore.messagecenter.dao.basedata.MdAppDao;
import com.dshore.messagecenter.model.basedata.MdApp;
import com.dshore.messagecenter.model.basedata.MdAppType;
import com.dshore.messagecenter.model.system.ResponseResult;
import com.dshore.messagecenter.model.topicqueue.MdTopicAccess;
import com.dshore.messagecenter.model.topicqueue.MdTopicSend;
import com.dshore.messagecenter.service.basedata.MdAppService;
import com.dshore.messagecenter.util.Page;
import com.dshore.messagecenter.util.RabbitUtil;
import com.dshore.messagecenter.util.UUIDUtil;
import com.dshore.messagecenter.util.secret.RSAManager;
import com.dshore.messagecenter.util.secret.SecretKey;
import com.github.pagehelper.util.StringUtil;
@Service
public class MdAppServiceImpl implements MdAppService{
	@Autowired
	private MdAppDao mcApplyDao;
	@Autowired
	private RabbitUtil rabbitUtil;
	/**
	 * 分页
	 */
	@Override
	public Page<MdApp> queryPageByParam(MdApp mcApply) {
	    Long total=mcApplyDao.queryCountMcAPP(mcApply);
		if(total<=mcApply.getLimit()||total<mcApply.getOffset()) {
			mcApply.setOffset(0);
		}
		List<MdApp> rows=mcApplyDao.queryListMcAPP(mcApply);
		Page<MdApp> page=new Page<MdApp>(mcApply.getLimit(), total, mcApply.getOffset(), rows);
		return page;
	}
	/**
	 * 查询网络状态（外网/内网)
	 */
	@Override
	public List<MdApp> selectByInternetType() {
		return mcApplyDao.selectByInternetType();
	}
	/**
	 * 编码自增
	 */
	@Override
	public MdApp checkCode() {
			List<MdApp>mdapp=mcApplyDao.checkCode();
	        String newEquipmentNo=null;
	        if(mdapp.size()==0) {
	        	newEquipmentNo="App" + String.format("%06d", 1);
	        	MdApp mdapps=new MdApp();
	        	mdapps.setAppCode(newEquipmentNo);
	        	return mdapps;
	        }else {
		      String equipmentNo=mdapp.get(0).getAppCode().substring(3);
		      int newEquipment = Integer.parseInt(equipmentNo) + 1;
		      newEquipmentNo = "App" + String.format("%06d", newEquipment);
		      mdapp.get(0).setAppCode(newEquipmentNo);
		      return mdapp.get(0);
	        }
	}
	
	
	/**
	 * 新增
	 */
	@Override
	public ResponseResult<Void> save(MdApp mcApply) {
		ResponseResult<Void>responseResult=new ResponseResult<>(200, "ok");
		String pubkey = null;
		String prikey = null;
		try {
			SecretKey SecretKey = RSAManager.generateKeyPair();
				pubkey = RSAManager.getClientPublicKeyStr(SecretKey).replaceAll("\r\n", "");
				prikey = RSAManager.getClientPrivateKeyStr(SecretKey).replaceAll("\r\n", "");
		} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			}
					/*String pubkey = AESGCMUpdateAAD2.createKey();*/
	    			String person="user-"+UUIDUtil.getUUId().substring(0, 5);
	    			String keyset=UUIDUtil.getUUId();
	    			String queue_netkey=person+","+keyset;
	    			mcApply.setQueueKey(queue_netkey);
	    			mcApply.setServicePubKey(pubkey);
	    			mcApply.setServicePriKey(prikey);
	    			Integer index=mcApplyDao.selectByAppCode(mcApply.getAppCode());
	    			Integer index2=mcApplyDao.selectByAppName(mcApply.getAppName());
	    			if(index!=0) {
	    				responseResult.setState(400);
	    				responseResult.setMessage("失败");
	    			}else if(index2!=0){
	    				responseResult.setState(400);
	    				responseResult.setMessage("失败");
	    			}else {
	    				Integer num=mcApplyDao.insertMcAPP(mcApply);
	    				rabbitUtil.createUser(person, keyset);
	    				if(num<=0) {
	    					responseResult.setState(400);
	    					responseResult.setMessage("失败");
	    				}
	    			}
		return responseResult;
	}
	/**
	 * 查询应用分类（三集五大）
	 */
	@Override
	public List<MdAppType> selectByAppType() {
		List<MdAppType>mdApp= mcApplyDao.selectByAppType();
		return mdApp;
	}
	/**
	 * 密钥重置
	 */
	@Override
	public ResponseResult<Void> keyreset(String id) {
		ResponseResult<Void>responseResult=new ResponseResult<>(200, "ok");
		/*String pubkey = AESGCMUpdateAAD2.createKey();*/
		MdApp mdApp=mcApplyDao.selectByqueuekey(id);
		String queue=mdApp.getQueueKey();
		String person="user-"+UUIDUtil.getUUId().substring(0, 5);
		String keyset=UUIDUtil.getUUId();
		String key=person+","+keyset;
		String pubkey = null;
		String prikey = null;
		try {
			SecretKey SecretKey = RSAManager.generateKeyPair();
			pubkey = RSAManager.getClientPublicKeyStr(SecretKey).replaceAll("\r\n", "");
			prikey = RSAManager.getClientPrivateKeyStr(SecretKey).replaceAll("\r\n", "");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		//查询该应用在目标应用表中的集合
		Integer num=mcApplyDao.updateKeyBySendApp(id);
		//查询该应用在接入应用表中的集合
		Integer  mdtopicAccess=mcApplyDao.updateKeyByAccessApp(id);
		if(num!=0||mdtopicAccess!=0) {
			responseResult.setMessage("含有该应用的主题队列已发布，无法重置！");
		    responseResult.setState(110);
			return  responseResult;
		}else {
			Integer i=mcApplyDao.updatekey(pubkey,id,key,prikey);
			rabbitUtil.deleteUser(queue.split(",")[0]);
			rabbitUtil.createUser(person, keyset);
			if(i<=0) {
				responseResult.setState(400);
				responseResult.setMessage("失败");
			}
			return responseResult;
		}
	}
/**
 * 根据id查询
 */
@Override
public ResponseResult<MdApp> getById(String id) {
	ResponseResult<MdApp>responseResult=new ResponseResult<>(200, "ok");
	if(mcApplyDao.getByIdOfNum(id)!=1) {
		responseResult.setState(400);
		responseResult.setMessage("失败");
	}else {
		responseResult.setData( mcApplyDao.getById(id));
	}
	return responseResult;
}
/**
 * 修改
 */
@Override
public ResponseResult<Void> midify(MdApp mcApply) {
	ResponseResult<Void>responseResult=new ResponseResult<>(200, "ok");
	List<MdApp>mda=mcApplyDao.checkName(mcApply.getAppName());
	if(mda.size()>1) {
		responseResult.setState(400);
		responseResult.setMessage("失败");
	}else if(mda.size()==0) {
				if(mcApplyDao.getByIdOfCode(mcApply.getId()).equals(mcApply.getAppCode())) {
					Integer i= mcApplyDao.modify(mcApply);
					if(i<0) {
						responseResult.setState(400);
						responseResult.setMessage("失败");
					}
	   	 		}else {
	   	 			responseResult.setState(400);
				    responseResult.setMessage("失败");
	   	 		}
	}else if(mda.size()==1){
		if(mda.get(0).getId().equals(mcApply.getId())){
			if(mcApplyDao.getByIdOfCode(mcApply.getId()).equals(mcApply.getAppCode())) {
				Integer i= mcApplyDao.modify(mcApply);
				if(i<0) {
					responseResult.setState(400);
					responseResult.setMessage("失败");
				}
   	 		}else {
   	 			responseResult.setState(400);
			    responseResult.setMessage("失败");
   	 		}
		}else {
			responseResult.setState(400);
		    responseResult.setMessage("失败");
		}
	}
	return responseResult;
}
/**
 * 批量删除
 */
@Override
public ResponseResult<Void> deleteAll(String id) {
	ResponseResult<Void>responseResult=new ResponseResult<>(200, "ok");
	try{
		String []ids=id.split(",");
		List<Map<String,Object>>mdApp=mcApplyDao.selectAll(ids);
		for(int i=0;i<mdApp.size();i++) {
		   //查询该应用在目标应用表中的集合
		  List<MdTopicSend> mdtopicsend=mcApplyDao.selectBySendApp((String)mdApp.get(i).get("id"));
			//查询该应用在接入应用表中的集合
		  List<MdTopicAccess> mdtopicAccess=mcApplyDao.selectByAccessApp((String)mdApp.get(i).get("id"));
			if(mdtopicsend.size()>0||mdtopicAccess.size()>0) {
				responseResult.setMessage("主题队列含有应用，无法删除！");
				responseResult.setState(110);
				return  responseResult;
			}
			}
			for(int i=0;i<mdApp.size();i++) {
				String use=(String)mdApp.get(i).get("queue_key");
	   			String [] users=use.split(",");
	   			String user=users[0];
	   			rabbitUtil.deleteUser(user);
	   		}
			mcApplyDao.deleteAll(ids);
			return responseResult;
		}catch(Exception e) {
			e.printStackTrace();
			responseResult.setState(400);
			responseResult.setMessage("失败");
			return responseResult;	
		}
	}
	/**
	 * 根据id下载队列密钥
	 */
	@Override
	public void  queuekey(String id,HttpServletResponse response) {
		try {
			MdApp mdapp= mcApplyDao.selectByqueuekey(id);
			String appName=mdapp.getAppName();
			String key=mdapp.getQueueKey();
			String person=key.split(",")[0]+"\n\t";
			String keyset=key.split(",")[1];
			String word=person+keyset;
			BufferedOutputStream bos = null;
			response.setContentType("multipart/form-data");
			response.setCharacterEncoding("utf-8");
	        response.setHeader("Content-disposition", "attachment; filename="
	        +URLEncoder.encode(appName +"队列密钥.CRT", "UTF-8"));
			bos = new BufferedOutputStream(response.getOutputStream());
			bos.write(word.getBytes());
			bos.flush();
			bos.close();
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	//根据id下载服务密钥
	@Override
	public void servicekey(String id,HttpServletResponse response) {
		try{
			MdApp mdApp=mcApplyDao.selectByservicekey(id);
			BufferedOutputStream bos = null;
			response.setContentType("multipart/form-data");
			response.setCharacterEncoding("utf-8");
			response.setHeader("Content-disposition", "attachment; filename=" 
			+URLEncoder.encode(mdApp.getAppName() +"服务密钥.CRT", "UTF-8"));
			bos = new BufferedOutputStream(response.getOutputStream());
			bos.write(mdApp.getServicePubKey().getBytes());
			bos.flush();
			bos.close();
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	//树状图
	@Override
	public String gettree() {
		List<MdAppType>mdAppType=mcApplyDao.selectByParentTree();
		StringBuilder treejson=new StringBuilder();
		treejson.append("[");
		for(int i=0;i<mdAppType.size();i++) {
			treejson.append("{\"id\":\"");
			treejson.append(mdAppType.get(i).getDictCode());
			treejson.append("\",\"name\":\"");
			treejson.append(mdAppType.get(i).getDictName());
				treejson.append("\",\"pId\":\"");
					treejson.append("");
				if(i==0) {
					treejson.append("\"");
					treejson.append(",\"open\":true}");
				}else {
					treejson.append("\"}");
				}
			if(i!=mdAppType.size()-1) {
				treejson.append(",");
			}
		}
		List<MdApp>mcApply=mcApplyDao.selectByTree();
		if(mcApply!=null&&!mcApply.isEmpty()) {
			treejson.append(",");
			for(int i=0;i<mcApply.size();i++) {
				treejson.append("{\"id\":\"");
				treejson.append(mcApply.get(i).getId());
				treejson.append("\",\"name\":\"");
				treejson.append(mcApply.get(i).getAppName());
				treejson.append("\",\"pId\":\"");
				treejson.append(mcApply.get(i).getAppType());
				treejson.append("\"}");
				if(i!=mcApply.size()-1) {
					treejson.append(",");
				}
			}
		}
		treejson.append("]");
		return treejson.toString();
	}
	//新增时校验应用名称
	@Override
	public String checkName(String appName,String id) {
		if(StringUtils.isNotBlank(appName.trim())) {
			List<MdApp>mdapp=mcApplyDao.checkName(appName);
			if(StringUtil.isEmpty(id)) {
				if(mdapp.size()==0) {
					return "true";
				}else {
					return "false";	
				}
			}else{
				if(mdapp.size()==0) {
					return "true";
				}else if(mdapp.size()==1){
					if(mdapp.get(0).getId().equals(id)) {
						return "true";
					}else {
						return "false";
						}
				}else {
					return "false";	
				}
			}
		}else {
			return "false";	
		}
	}
}

